package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"time"
)

func main() {
	// 修改环境变量 key，添加 PLUGIN_ 前缀
	apiVersion := os.Getenv("PLUGIN_API_VERSION")
	fmt.Println("apiVersion:", apiVersion)
	accessToken := os.Getenv("PLUGIN_ACCESS_TOKEN")
	fmt.Println("accessToken:", accessToken)
	projectID := os.Getenv("PLUGIN_PROJECT_ID")
	fmt.Println("projectID:", projectID)
	inputUrl := os.Getenv("PLUGIN_INPUT_URL")
	fmt.Println("inputUrl:", inputUrl)
	locale := os.Getenv("PLUGIN_LOCALE")
	fmt.Println("locale:", locale)
	targetEndpointFolderId := os.Getenv("PLUGIN_STARGET_ENDPOINT_FOLDER_ID")
	fmt.Println("targetEndpointFolderId:", targetEndpointFolderId)
	targetSchemaFolderId := os.Getenv("PLUGIN_TARGET_SCHEMA_FOLDER_ID")
	fmt.Println("targetSchemaFolderId:", targetSchemaFolderId)
	endpointOverwriteBehavior := os.Getenv("PLUGIN_ENDPOINT_OVERWRITE_BEHAVIOR")
	fmt.Println("endpointOverwriteBehavior:", endpointOverwriteBehavior)
	schemaOverwriteBehavior := os.Getenv("PLUGIN_SCHEMA_OVERWRITE_BEHAVIOR")
	fmt.Println("schemaOverwriteBehavior:", schemaOverwriteBehavior)
	updateFolderOfChangedEndpoint := os.Getenv("PLUGIN_UPDATE_FOLDER_OF_CHANGED_ENDPOINT")
	fmt.Println("updateFolderOfChangedEndpoint:", updateFolderOfChangedEndpoint)
	prependBasePath := os.Getenv("PLUGIN_PREPEND_BASE_PATH")
	fmt.Println("prependBasePath:", prependBasePath)
	maxRetriesStr := os.Getenv("PLUGIN_MAX_RETRIES")
	fmt.Println("maxRetries:", maxRetriesStr)
	retryDelayStr := os.Getenv("PLUGIN_RETRY_DELAY")
	fmt.Println("retryDelay:", retryDelayStr)

	// 构建请求体
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"url": inputUrl,
		},
		"options": map[string]interface{}{
			"targetEndpointFolderId":        targetEndpointFolderId,
			"targetSchemaFolderId":          targetSchemaFolderId,
			"endpointOverwriteBehavior":     endpointOverwriteBehavior,
			"schemaOverwriteBehavior":       schemaOverwriteBehavior,
			"updateFolderOfChangedEndpoint": updateFolderOfChangedEndpoint == "true",
			"prependBasePath":               prependBasePath == "true",
		},
	}

	body, err := json.Marshal(requestBody)
	if err != nil {
		os.Exit(1)
	}

	maxRetries := 10
	if maxRetriesStr != "" {
		maxRetries, _ = strconv.Atoi(maxRetriesStr)
	}

	retryDelay := 1 * time.Second
	if retryDelayStr != "" {
		retryDelay, _ = time.ParseDuration(retryDelayStr)
	}

	isSuccess := false
	for i := 0; i < maxRetries; i++ {
		req, err := http.NewRequest(
			http.MethodPost,
			fmt.Sprintf("https://api.apifox.com/v1/projects/%s/import-openapi?locale=%s", projectID, locale),
			bytes.NewBuffer(body),
		)
		if err != nil {
			fmt.Println("Error creating request:", err)
			os.Exit(1)
		}
		// 添加 X-Apifox-Api-Version header
		req.Header.Add("X-Apifox-Api-Version", apiVersion)
		// 添加 Authorization header
		req.Header.Add("Authorization", "Bearer "+accessToken)
		// 设置 Content-Type
		req.Header.Set("Content-Type", "application/json")

		// 发送请求
		resp, err := http.DefaultClient.Do(req)
		if err == nil && resp.StatusCode == http.StatusOK {
			isSuccess = true
			fmt.Println("update doc success")
			break // 请求成功，退出循环
		}
		// 打印resp body
		defer resp.Body.Close()
		body, _ := io.ReadAll(resp.Body)
		fmt.Println("Response status:", resp.StatusCode)
		fmt.Printf("Response body: %s\n", string(body))

		fmt.Printf("Request failed (attempt %d): %v\n", i+1, err)
		if i < maxRetries-1 {
			time.Sleep(retryDelay) // 等待后再重试
		}
	}

	if !isSuccess {
		fmt.Printf("All retries failed, update doc failed\n")
		os.Exit(1)
	}

	return
}
